package class22;

/**
 * @author zhangchaoliang
 * create 2022
 */
public class PrintMatrixSpiralOrder {

    public static void spiralOrderPrint(int[][] matrix){
        int tr = 0;
        int tc = 0;
        int dr = matrix.length-1;
        int dc = matrix[0].length-1;
        while (tr <=dr && tc <= dc){
            printEdge(matrix,tr++,tc++,dr--,dc--);
        }
    }

    public static void printEdge(int[][] m,int a,int b,int c,int d){
        if (a==c){
            for (int i=b;i<=d;i++)
                System.out.print(m[a][i] + " ");
        }else if (b == d){
            for (int i =a;i<=c;i++){
                System.out.print(m[i][b]+" ");
            }
        }else {
            int curr=a;
            int curc=b;
            while (curc != d){
                System.out.print(m[a][curc]+ " ");
                curc++;
            }

            while (curr != c){
                System.out.print(m[curr][d]+" ");
                curr++;
            }
            while (curc !=b){
                System.out.print(m[c][curc]+" ");
                curc--;
            }
            while (curr!=a){
                System.out.print(m[curr][b]+" ");
                curr--;
            }
        }
    }

    public static void main(String[] args) {
        int[][] matrix = {
                { 1, 2, 3, 4 },
                { 5, 6, 7, 8 },
                { 9, 10, 11, 12 },
                { 13, 14, 15, 16 } };
        spiralOrderPrint(matrix);
    }
}
